package com.qiku.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qiku.constants.SystemConstants;
import com.qiku.entity.Article;
import com.qiku.entity.Category;
import com.qiku.entity.ResponseResult;
import com.qiku.service.CategoryService;
import com.qiku.utils.BeanCopyUtils;
import com.qiku.vo.ArticleDetailVo;
import com.qiku.vo.ArticleListVo;
import com.qiku.vo.HotArticleVo;
import com.qiku.mapper.ArticleMapper;
import com.qiku.service.ArticleService;
import com.qiku.vo.PageVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询热门文章  浏览量前十的文章
     * @return
     */
    @Override
    public ResponseResult hotArticleList() {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper();
        //查询条件  正式文章即：状态为0
        queryWrapper.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL);
        // 按照浏览量排序
        queryWrapper.orderByDesc(Article::getViewCount);
        //最多显示十条  1当前页  10 条数
        Page<Article> page = new Page(1,10);
        page(page,queryWrapper);
        List<Article> articleList = page.getRecords();
//        List<HotArticleVo> list = BeanCopyUtils.copyBeanList(articleList,HotArticleVo.class);

        List<HotArticleVo> list = new ArrayList<>();
        HotArticleVo vo = new HotArticleVo();
        for (Article article : articleList){
            //从redis中获取viewCount
            setViewCount(article);
            BeanUtils.copyProperties(article,vo);
            list.add(vo);
        }
        // 结果封装
        return ResponseResult.okResult(list);
    }

    @Override
    public ResponseResult articleList(Integer pageNum, Integer pageSize, Long categoryId) {
        //查询条件
        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
        // 如果有 categoryId 就要查询和传入的相同
        wrapper.eq(categoryId != null&&categoryId>0,Article::getCategoryId,categoryId);
        // 状态是发布的文章
        wrapper.eq(Article::getStatus,SystemConstants.ARTICLE_STATUS_NORMAL);
        //对isTop降序
        wrapper.orderByDesc(Article::getIsTop);
        //分页查询
        Page<Article> page = new Page<>(pageNum,pageSize);
        page(page,wrapper);
        List<Article> articles = page.getRecords();
//        List<Article> articleList = articles.stream()
//                .map(article -> article.setCategoryName(categoryService.getById(article.getCategoryId()).getName()))
//                .collect(Collectors.toList());
        //articleId 去查询articleName进行设置
        //封装查询结果
        List<ArticleListVo> ArticleListVos = new ArrayList<>();
        for (Article article : articles){
            //从redis中获取viewCount
            setViewCount(article);
            Category category = categoryService.getById(article.getCategoryId());
            article.setCategoryName(category.getName());
            ArticleListVo vo = new ArticleListVo();
            BeanUtils.copyProperties(article,vo);
            ArticleListVos.add(vo);
        }
        PageVo pageVo = new PageVo(ArticleListVos,page.getTotal());
        return ResponseResult.okResult(pageVo);
    }


    @Override
    public ResponseResult getArticleDetail(Long id) {
        // 根据id查询文章
        Article article = getById(id);
        //从redis中获取viewCount  封装成方法
        setViewCount(article);
        // 转换成Vo
        ArticleDetailVo articleDetailVo = new ArticleDetailVo();
        BeanUtils.copyProperties(article, articleDetailVo);
        // 根据分类id查询分类名  并赋值
        Long categoryId = articleDetailVo.getCategoryId();
        Category category = categoryService.getById(categoryId);
        if (null != category){
            articleDetailVo.setCategoryName(category.getName());
        }
        // 封装响应
        return ResponseResult.okResult(articleDetailVo);
    }

    @Override
    public ResponseResult updateViewCount(Long id) {
        //更新redis中  对应的浏览量
        redisTemplate.opsForHash().increment("articleViewCount",id,1);
        return ResponseResult.okResult();
    }

    /**
     * 封装从redis中获取viewCount 的方法
     * 从redis中获取viewCount 更新浏览量
     * @param article
     */
    private void setViewCount(Article article){
        Map<Long,Integer> viewCountMap = redisTemplate.opsForHash().entries("articleViewCount");
        Long viewCount = viewCountMap.get(article.getId()).longValue();
        article.setViewCount(viewCount);
    }

}
